package com.mkr.servlet;

import com.mkr.entity.Book;
import com.mkr.service.BookService;
import com.mkr.service.impl.BookServiceImpl;
import com.mkr.util.MyUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author mkr
 * @version V1.0
 * @Project BookApp
 * @Package ${PACKAGE_NAME}
 * @Description: ${TODO}
 * @Date 2022/5/14 19:24
 */
@WebServlet(name = "AddBookServlet" , urlPatterns = "/addBook")
public class AddBookServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();

        //获取参数
        String bookname = request.getParameter("bookname");
        String author = request.getParameter("author");
        String description = request.getParameter("description");
        Double price = Double.valueOf(request.getParameter("price"));
        String publishers = request.getParameter("publishers");

        if (MyUtil.isEmpty(bookname)){
            session.setAttribute("msg", "书名不能为空");
            response.sendRedirect(request.getContextPath()+"/addBook.jsp");
            return;
        }
        if (MyUtil.isEmpty(author)){
            session.setAttribute("mag", "作者不能为空");
            response.sendRedirect(request.getContextPath()+"/addBook.jsp");
            return;
        }

        Book book = new Book(null,bookname,author,description,price,publishers);
        //调用业务层，将书籍添加到数据库中
        BookService bookService = new BookServiceImpl();
        boolean result = bookService.addOne(book);

        if (result){
            //添加成功，显示新的列表
            response.sendRedirect(request.getContextPath()+"/bookList");
        }else {
            //添加失败
            session.setAttribute("mag", "添加失败");
            response.sendRedirect(request.getContextPath()+"/addBook.jsp");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
